package in.co.codedoc.time;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Time
	implements Comparable<Time>
{
	public Time()
	{
		this(new GregorianCalendar());
	}
	
	public Time(int millis)
	{
		this.millisNumber = millis;
	}

	public Time(Calendar daytime)
	{
		this
		(
			daytime.get(Calendar.HOUR_OF_DAY),
			daytime.get(Calendar.MINUTE),
			daytime.get(Calendar.SECOND),
			daytime.get(Calendar.MILLISECOND)
		);
	}
	
	public Time(int hour,int minute,int sec)
	{
		this(hour, minute, sec, 0);
	}
	
	public Time(int hour,int minute,int sec,int millis)
	{
		this.millisNumber = GetMillisNumber(hour,minute,sec,millis);
	}
	
	public int GetMillisNumber()
	{
		return millisNumber;
	}
	
	public int GetHours()
	{
		return millisNumber / MILLIS_PER_HOUR;
	}

	public int GetMinutes()
	{
		return (millisNumber % MILLIS_PER_HOUR) / MILLIS_PER_MINUTE;
	}

	public int GetSeconds()
	{
		return (millisNumber % MILLIS_PER_MINUTE) / MILLIS_PER_SEC;
	}
	
	public int GetMillis()
	{
		return millisNumber % MILLIS_PER_SEC;
	}
	
	public boolean IsBefore(Time time)
	{
		return millisNumber < time.millisNumber;
	}
	
	public boolean IsAfter(Time time)
	{
		return millisNumber > time.millisNumber;
	}
	
	@Override
	public boolean equals(Object t)
	{
		if(t == null ||!(t instanceof Time))
		{
			return false;
		}
		
		Time that = (Time)t;
		
		return millisNumber == that.millisNumber;
	}
	
	@Override
	public int hashCode()
	{
		return millisNumber;
	}
	
	@Override
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();
		
		buffer.append(GetHours())
				.append(':')
				.append(GetMinutes())
				.append(':')
				.append(GetSeconds())
				.append('.')
				.append(GetMillis());
				
		return buffer.toString();
	}
	
	@Override
	public int compareTo(Time that)
	{
		return 
			millisNumber < that.millisNumber
				? 
					-1
				:
					(
						millisNumber > that.millisNumber
						?
							+1
						:
							0
					)
				;
	}
	
	private static final int GetMillisNumber(int hour, int minute, int sec, int millis)
	{
		return (hour * MILLIS_PER_HOUR + minute * MILLIS_PER_MINUTE + sec * MILLIS_PER_SEC + millis)
				%MILLIS_PER_DAY;
	}

	private int millisNumber;
	private static final int MILLIS_PER_SEC = 1000;	
	private static final int MILLIS_PER_MINUTE = MILLIS_PER_SEC * 60;
	private static final int MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60;
	private static final int MILLIS_PER_DAY = MILLIS_PER_HOUR * 60;
}
